using System;
using Mono.Unix;
using Gtk;
using Tomboy;
using Google.GData.Client;
using System.Collections.Generic;

namespace Tomboy.GoogleNoteBookSync {
	public class GoogleNoteBookSyncNoteAddin : NoteAddin {
		Gtk.MenuItem item;
		string user_id;

		public override void Initialize ()
		{
			LoadPreferences ();
			item = new Gtk.MenuItem (Catalog.GetString ("Sync to Google Notebook"));
			item.Activated += OnMenuItemActivated;
			item.Show ();
			AddPluginMenuItem (item);
		}

		public override void Shutdown ()
		{
			item.Activated -= OnMenuItemActivated;
			SavePreferences ();
		}

		public override void OnNoteOpened ()
		{
		}

		void OnMenuItemActivated (object sender, EventArgs args)
		{
			Logger.Log("Getting the note manager");
			NoteManager noteManager = Manager;
			Logger.Log("Got the note manager");

			// Create a query and service object:
			FeedQuery query = new FeedQuery();
			Service service = new Service("nb", "tomboyCo-tomboyPlugin-1");

			// Set your credentials:
			service.setUserCredentials("", "");

			try {
				
				// Create the query object:
				query.Uri = new Uri("http://www.google.com/notebook/feeds/" + userid);

				// Tell the service to query:
				AtomFeed noteBookListFeed = service.Query(query);
				if (noteBookListFeed.Entries.Count > 0) {
					AtomEntry noteBookListFeedEntry = noteBookListFeed.Entries[0]; 
					AtomUri myNoteBookUri = noteBookListFeedEntry.Content.Src; 
					query.Uri = new Uri(myNoteBookUri.Content);
					AtomFeed noteBookFeed = service.Query(query);
					Logger.Log(noteBookFeed.Entries.Count.ToString());
					for(int noteBookFeedEntry = 0; noteBookFeedEntry < noteBookFeed.Entries.Count; noteBookFeedEntry++) {
						Logger.Log(noteBookFeedEntry.ToString());
						AtomEntry noteBookEntry = noteBookFeed.Entries[noteBookFeedEntry];
						String noteEntryTitle = noteBookEntry.Title.Text;
						String noteEntryContents = noteBookEntry.Content.Content;
						DateTime noteEntryUpdated = noteBookEntry.Updated;

						noteEntryContents = noteEntryContents.Replace("&", "&amp;").Replace("<", "&lt;").Replace(">", "&gt;");
						noteEntryContents = "<note-content>" + noteEntryTitle + "\n\n" + noteEntryContents + "</note-content>";

						Note localNote = noteManager.Find(Catalog.GetString(noteEntryTitle));
						if (localNote == null) {
							Logger.Log("Note " + noteEntryTitle + " doesn't exist.  Creating.");
							Note googleNote = noteManager.Create (Catalog.GetString(noteEntryTitle), noteEntryContents);
							googleNote.QueueSave(ChangeType.ContentChanged);
						} else {
							Logger.Log("Note " + noteEntryTitle + " exists.");
							DateTime localNoteChanged = localNote.ChangeDate;
							if (localNoteChanged.CompareTo(noteEntryUpdated) < 0) {
								NoteData localNoteData = localNote.Data;
								Logger.Log("\tUpdating contents of note.");
								localNoteData.Text = noteEntryContents;
							}
							localNote.QueueSave(ChangeType.ContentChanged);
						}
					}
				}
			} catch (Exception e) {
				Logger.Warn ("Error fetching atom feed: {0}", e);
				System.Environment.Exit(0);
			}

			/* try {
				List<Note> localNotes = noteManager.Notes;
				foreach( Note localNote in localNotes ) {
				
					AtomEntry entry = new AtomEntry();
					AtomPerson author = new AtomPerson(AtomPersonType.Author);
					author.Name = ""; 
					author.Email = "";
					entry.Authors.Add(author);
					entry.Title.Text = localNote.Title; 
					entry.Content.Content = localNote.TextContent;

					Uri postUri = new Uri("http://www.google.com/notebook/feeds/" + userid + "/private/full");

					// Send the request and receive the response:
					AtomEntry insertedEntry = service.Insert(postUri, entry);
				}

			} catch (Exception e) {
				Logger.Warn ("Error submitting existing notes: {0}", e);
				System.Environment.Exit(0);
			} */
		}

		protected void SavePreferences ()
		{
			Preferences.Set ("/apps/tomboy/google_notebook_userid", userid);
		}

		protected void LoadPreferences ()
		{
			try {
				userid = (string) Preferences.Get ("/apps/tomboy/google_notebook_userid");
			} catch (Exception e) {
				Logger.Warn ("Error loading preferences: {0}\n{1}",
						e.Message, e.StackTrace);
			}
		}

		public string userid
		{
			get {
				return user_id;
			}
			set {
				user_id = value;
			}
		}
	}

	public class GoogleNoteBookSyncPreferences : Gtk.VBox
	{
		Gtk.Button open_template_button;

		public GoogleNoteBookSyncPreferences ()
			: base (false, 12)
		{
			Gtk.Label label = new Gtk.Label (
					Catalog.GetString (
						"Change the <span weight=\"bold\">Today: Template</span> " +
						"note to customize the text that new Today notes have."));
			label.UseMarkup = true;
			label.Wrap = true;
			label.Show ();
			PackStart (label, true, true, 0);

			open_template_button = new Gtk.Button (
					Catalog.GetString ("_Open Today: Template"));
			open_template_button.UseUnderline = true;
			open_template_button.Show ();
			PackStart (open_template_button, false, false, 0);

			ShowAll ();
		}
	}
}
